"use strict"

/**
 * 数据库存储接口
 *  
 */

var mysql = require("mysql");

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '4511123',
    port: 3306,
    database: 'crawler4zb'
});

var db = {
    version: "1.0.0",
    name: "crawler db support [mysql]",
    host: "",
    database: "",
    user: "",
    password: "",
    open: function () {
        connection.connect();
    },
    close: function () {
        connection.end();
    },
    insert: function (cond, cb) {
        connection.query("INSERT INTO items SET ?", cond, cb);
    },
    update: function (cond, cb) {
        var sql = "UPDATE items SET ? ";
        var where = null;
        for (var k in cond) {
            if (k == "id") {
                where = " where id=" + cond[k];
                delete cond[k];
                continue;
            }
        }
        if (where)
            sql = sql + where;
        connection.query(sql, cond, cb);
    },
    find: function (cond, cb) {
        var sql = "SELECT * FROM items WHERE 1=1 "
        for (var k in cond) {
            var v = cond[k];
            if (typeof v === "string")
                sql = sql + " AND " + k + "='" + v + "'";
            else
                sql = sql + " AND " + k + "=" + v;
        }
        connection.query(sql, cb);
    },
    query: function (sql, cb) {
        connection.query(sql, cb);
    },
    findOne: function (cond, cb) {
        var sql = "SELECT * FROM items WHERE 1=1 "
        for (var k in cond) {
            var v = cond[k];
            if (typeof v === "string")
                sql = sql + " AND " + k + "='" + v + "'";
            else
                sql = sql + " AND " + k + "=" + v;
        }
        sql = sql + " limit 1";
        return connection.query(sql, cb);
    },
    findAll: function (cb) {
        var sql = "SELECT * FROM items";
        return connection.query(sql, cb);
    }
};

exports = module.exports = db;
